package my.set;

import my.util.LinkedList;
import my.util.List;

/**
 * <p>
 * 用链表实现集合
 * </p>
 *
 * @author AJun
 * @since 2020/8/31
 */
@SuppressWarnings("unused")
public class ListSet<E> implements Set<E> {

    private final List<E> list = new LinkedList<>();

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public void clear() {
        list.clean();
    }

    @Override
    public boolean contains(E element) {
        return list.contains(element);
    }

    @Override
    public void add(E element) {
        // 如果包含 element 就直接返回
        /*if (list.contains(element)) {
            return;
        }
        list.add(element);*/

        // 做法2: 如果存在则用新的 element 覆盖旧值，否则按新的添加
        int index = list.indexOf(element);
        if (index != -1) {
            list.set(index, element);
        } else {
            list.add(element);
        }
    }

    @Override
    public void remove(E element) {
        list.remove(element);
    }

    @Override
    public void traversal(Visitor<E> visitor) {
        if (visitor == null) {
            return;
        }

        for (E e : list) {
            // 如果遍历完毕返回true则停止遍历
            if (visitor.visit(e)) {
                return;
            }
        }
    }

}
